import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Home.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/article/:id',
      name: 'article-detail',
      component: () => import('../views/ArticleDetail.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/backend',
      name: 'backend',
      component: () => import('../views/Backend.vue'),
      meta: { requiresAuth: true },
      redirect: '/backend/articles',
      children: [
        {
          path: 'articles',
          name: 'article-manage',
          component: () => import('../views/backend/ArticleManagement.vue')
        },
        {
          path: 'categories',
          name: 'category-manage',
          component: () => import('../views/backend/CategoryManagement.vue'),
          meta: { requiresAdmin: true }
        },
        {
          path: 'audit',
          name: 'article-audit',
          component: () => import('../views/backend/ArticleAudit.vue'),
          meta: { requiresAdmin: true }
        },
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/backend/Dashboard.vue'),
          meta: { requiresAdmin: true }
        },
        {
          path: 'users',
          name: 'user-manage',
          component: () => import('../views/backend/UserManagement.vue'),
          meta: { requiresAdmin: true }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('role')

  if (to.meta.requiresAuth && !token) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (to.meta.requiresAdmin && userRole !== 'ADMIN') {
    next('/')
  } else {
    next()
  }
})

export default router 